package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.service.IDeclarationService;
import com.mdd.admin.validate.DeclarationCreateValidate;
import com.mdd.admin.validate.DeclarationUpdateValidate;
import com.mdd.admin.validate.DeclarationSearchValidate;
import com.mdd.admin.vo.DeclarationListedVo;
import com.mdd.admin.vo.DeclarationDetailVo;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.Declaration;
import com.mdd.common.mapper.DeclarationMapper;
import com.mdd.common.util.ListUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 申报条件实现类
 * @author LikeAdmin
 */
@Service
public class DeclarationServiceImpl implements IDeclarationService {
        
    @Resource
    DeclarationMapper declarationMapper;

    /**
     * 申报条件列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<DeclarationListedVo>
     */
    @Override
    public PageResult<DeclarationListedVo> list(PageValidate pageValidate, DeclarationSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        MPJQueryWrapper<Declaration> mpjQueryWrapper = new MPJQueryWrapper<>();

        // 判断 typeId 是否有值，如果有则添加查询条件
        if (searchValidate.getTypeId() != null && !searchValidate.getTypeId().equals("")) {
            mpjQueryWrapper.eq("t.type_id", searchValidate.getTypeId());
        }

        // 查询
        mpjQueryWrapper.selectAll(Declaration.class);
        mpjQueryWrapper.innerJoin("?_declaration_type dt ON dt.id=t.type_id".replace("?_", GlobalConfig.tablePrefix));
        mpjQueryWrapper.select("dt.type_name");
        mpjQueryWrapper.select("dt.type_field");
        mpjQueryWrapper.eq("t.is_delete", 0);
        mpjQueryWrapper.orderByDesc("id");

        // 调用自定义的 setSearch 方法进行进一步的查询处理
        declarationMapper.setSearch(mpjQueryWrapper, searchValidate, new String[]{
                "=:modifier:str",
                "=:creator:str",
                "=:code:str",
                "=:acceptancerequirments@acceptanceRequirments:str",
                "=:typeId@type_id:int",
        });

        // 执行分页查询
        IPage<DeclarationListedVo> iPage = declarationMapper.selectJoinPage(
                new Page<>(page, limit),
                DeclarationListedVo.class,
                mpjQueryWrapper);

        // 格式化时间字段
        for (DeclarationListedVo item : iPage.getRecords()) {
            item.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            item.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
        }

        // 返回分页结果
        return PageResult.iPageHandle(iPage);
    }

    /**
     * 申报条件详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return Declaration
     */
    @Override
    public DeclarationDetailVo detail(Integer id) {
        Declaration model = declarationMapper.selectOne(
                new QueryWrapper<Declaration>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        DeclarationDetailVo vo = new DeclarationDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 申报条件新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(DeclarationCreateValidate createValidate) {
        Declaration model = new Declaration();
        model.setCreator(createValidate.getCreator());
        model.setCode(createValidate.getCode());
        model.setAcceptancerequirments(createValidate.getAcceptancerequirments());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setTypeId(createValidate.getTypeId());
        model.setSymbol(createValidate.getSymbol());
        model.setAndsql(createValidate.getAndsql());
        model.setAndsqlName(createValidate.getAndsqlName());
        declarationMapper.insert(model);
    }

    /**
     * 申报条件编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(DeclarationUpdateValidate updateValidate) {
        Declaration model = declarationMapper.selectOne(
                new QueryWrapper<Declaration>()
                    .eq("id",  updateValidate.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setModifier(updateValidate.getModifier());
        model.setCreator(updateValidate.getCreator());
        model.setCode(updateValidate.getCode());
        model.setAcceptancerequirments(updateValidate.getAcceptancerequirments());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setTypeId(updateValidate.getTypeId());
        model.setSymbol(updateValidate.getSymbol());
        model.setAndsql(updateValidate.getAndsql());
        model.setAndsqlName(updateValidate.getAndsqlName());
        declarationMapper.updateById(model);
    }

    /**
     * 申报条件删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        Declaration model = declarationMapper.selectOne(
                new QueryWrapper<Declaration>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        declarationMapper.updateById(model);
    }

}
